package com.pug.service.message;

import com.pug.dto.UserDto;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * Author: lqm
 * create: 2022/5/7 19:14
 * Lover: lqx
 *
 * @see
 */
@Service
public class MessageMqSendUser {
    public static final String User_direct_queue="User_direct_queue";
    public static final String User_direct_exchange="User_direct_exchange";
    public static final String User_direct_key="User_direct_key";
    //用户登录将信息发送到mq
    @Resource
    RabbitTemplate rabbitTemplate;
    public void pushMessageSave(UserDto userDto){
        //设置编码
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        rabbitTemplate.setExchange(User_direct_exchange);
        rabbitTemplate.setRoutingKey(User_direct_key);
        rabbitTemplate.convertAndSend(userDto, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                MessageProperties messageProperties = message.getMessageProperties();
                //再将消息发送到mq的时候生成一个uuid先，不要使用mq自带的消息id了
                messageProperties.setMessageId(UUID.randomUUID().toString());
                //设置头信息 表示以MessageDto对象传过去
                messageProperties.setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME,UserDto.class);
                //设置持久化
                messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                return message;
            }
        });
    }
    //用户注册将信息发送到mq
}
